package com.xhwl.centiotdata.handler.talk.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xhwl.centiotdata.handler.talk.TalkIntegrationFactory;
import com.xhwl.centiotdata.handler.talk.TalkIntegrationHandler;
import com.xhwl.centiotdata.pojo.dto.device.DeviceIntegrationConfigDTO;
import com.xhwl.centiotdata.pojo.dto.mili.DeviceMiLiDTO;
import com.xhwl.centiotdata.pojo.dto.mili.DeviceMiLiYunDTO;
import com.xhwl.centiotdata.pojo.dto.mili.TalkLogDTO;
import com.xhwl.centiotdata.pojo.dto.talkback.TalkBackIntegrationConfigDTO;
import com.xhwl.centiotdata.service.IOrgInfoService;
import com.xhwl.centiotdata.service.cent.ICentTalkBackService;
import com.xhwl.centiotdata.service.cent.IDeviceCentService;
import com.xhwl.centiotdata.service.cent.IProjectCentService;
import com.xhwl.centiotdata.suppliersystem.mili.DeviceMiLiHandler;
import com.xhwl.centiotdata.suppliersystem.mili.TalkBackMiLiHandler;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.enums.ProductEnum;
import com.xhwl.common.enums.SupplierEnum;
import com.xhwl.common.enums.device.DeviceTypeEnum;
import com.xhwl.common.pojo.cent.iot.OrgInfo;
import com.xhwl.common.pojo.cent.sdata.Organization;
import com.xhwl.common.pojo.cent.talkback.TalkRecord;
import com.xhwl.common.query.cent.device.ProductAccessQuery;
import com.xhwl.common.query.cent.sdata.OrganizationQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: wuyuhao
 * @createDate: 2022/10/31 19:55
 */
@Service
public class TalkMiLiIntegrationHandler extends TalkIntegrationHandler {

    private static final Logger log = LoggerFactory.getLogger(TalkMiLiIntegrationHandler.class);

    @Autowired
    private DeviceMiLiHandler deviceMiLiHandler;

    @Autowired
    private TalkBackMiLiHandler talkBackMiLiHandler;

    @Autowired
    private IDeviceCentService deviceCentService;

    @Autowired
    private ICentTalkBackService talkBackService;

    @Autowired
    private IOrgInfoService iOrgInfoService;

    @Autowired
    private IProjectCentService iProjectCentService;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 米立云对讲
        TalkIntegrationFactory.register(ProductEnum.MILI_TALK_BACK.getId(), this);
    }

    @Override
    public void pullDevice(TalkBackIntegrationConfigDTO configDTO) {
        if (configDTO.getDeviceType() == null) {
            log.error("projectId: {} pullDevice failed! deviceType is null!", configDTO.getProjectId());
            return;
        }
        if (!configDTO.getDeviceType().equals(DeviceTypeEnum.TALK_BACK.getCode())) {
            return;
        }
        // 拉取数据
        DeviceIntegrationConfigDTO dto = new DeviceIntegrationConfigDTO();
        BeanUtils.copyProperties(configDTO, dto);
        List<DeviceMiLiDTO> deviceMiLiList = deviceMiLiHandler.pullDevice(dto);
        if (CollectionUtils.isEmpty(deviceMiLiList)) {
            return;
        }
        // 转换数据
        List<DeviceDTO> deviceDTOList = this.handleDevice(configDTO, deviceMiLiList);
        // 存储业务中台
        deviceCentService.asyncUpdateDevice(deviceDTOList);
    }

    private List<DeviceDTO> handleDevice(TalkBackIntegrationConfigDTO configDTO, List<DeviceMiLiDTO> deviceMiLiDTOList) {
        // 获取米立云对讲相关设备信息
        ProductAccessQuery productAccessQuery = new ProductAccessQuery();
        productAccessQuery.setProjectId(configDTO.getProjectId());
        productAccessQuery.setProductId(configDTO.getProductId());
        productAccessQuery.setCategoryId(configDTO.getCategoryEnum().getId());
        productAccessQuery.setSupplierId(SupplierEnum.MILI.getId());
        // 请求米立云的设备信息
        String token = talkBackMiLiHandler.getToken(configDTO.getTalk());
        List<DeviceMiLiYunDTO> miLiYunDTOList = talkBackMiLiHandler.getDeviceList(configDTO.getTalk(), token);
        Map<String, DeviceMiLiYunDTO> map = miLiYunDTOList.stream()
                .collect(
                        Collectors.toMap(
                                DeviceMiLiYunDTO::getDeviceCode,
                                e -> e
                        )
                );
        return deviceMiLiDTOList.stream()
                .map(deviceMiLiDTO -> {
                    DeviceDTO deviceDTO = new DeviceDTO();
                    deviceDTO.setProjectId(configDTO.getProjectId());
                    deviceDTO.setProductId(configDTO.getProductId());
                    deviceDTO.setCategoryId(configDTO.getCategoryEnum().getId());
                    deviceDTO.setDeviceTypeId(configDTO.getDeviceType());
                    deviceDTO.setName(deviceMiLiDTO.getDeviceDesc());
                    deviceDTO.setThirdDeviceId(deviceMiLiDTO.getDeviceNo());
                    deviceDTO.setOnlineStatus(deviceMiLiDTO.getOnline());
                    Integer spaceId = this.getSpaceId(deviceMiLiDTO.getFrameNo());
                    log.info("handleDevice->spaceId: {}", spaceId);
                    deviceDTO.setOrganizationId(spaceId);
                    // 供应商-米立
                    deviceDTO.setSupplierId(SupplierEnum.MILI.getId());
                    // 云对讲设备
                    JSONObject attributeJson = new JSONObject();
                    attributeJson.put("ip", deviceMiLiDTO.getIPAddr());
                    // 云对讲设备
                    attributeJson.put("miliyun", map.get(deviceMiLiDTO.getDeviceNo()));
                    // 米立设备类型1：区口机2：梯口机4：室内机
                    // 云对讲设备类型 1小区围墙机，2单元门口机，3室内机
                    if (1 == deviceMiLiDTO.getDeviceType()) {
                        attributeJson.put("DeviceType", 1);
                    } else if (2 == deviceMiLiDTO.getDeviceType()) {
                        attributeJson.put("DeviceType", 2);
                    } else if (4 == deviceMiLiDTO.getDeviceType()) {
                        attributeJson.put("DeviceType", 3);
                    }
                    deviceDTO.setAttributeJson(attributeJson);
                    return deviceDTO;
                })
                .collect(Collectors.toList());
    }

    public Integer getSpaceId(String frameNo) {
        log.info("getSpaceId->frameNo: {}", frameNo);
        if (frameNo.length() == 2 || frameNo.length() == 4) {
            List<OrgInfo> list = iOrgInfoService.list(new LambdaQueryWrapper<OrgInfo>()
                    .eq(OrgInfo::getOrgName, "mili")
                    .likeRight(OrgInfo::getOrgIndexCode, frameNo));
            Integer id = list.get(0).getId();
            OrganizationQuery query = new OrganizationQuery();
            query.withId(id);
            int level = 3;
            if (frameNo.length() == 2) {
                query.withRoundLevel(2);
                query.withLevel(Collections.singletonList(4));
            } else {
                query.withRoundLevel(1);
                query.withLevel(Collections.singletonList(5));
                level = 4;
            }
            List<Organization> organizations = iProjectCentService.organizationList(query);
            Integer orgId = null;
            for (Organization o : organizations) {
                if (o.getLevel() == level) {
                    orgId = o.getId();
                    break;
                }
            }
            return orgId;
        } else if (frameNo.length() == 8) {
            OrgInfo info = iOrgInfoService.getOne(new LambdaQueryWrapper<OrgInfo>()
                    .eq(OrgInfo::getOrgName, "mili")
                    .eq(OrgInfo::getOrgIndexCode, frameNo));
            return info.getId();
        }
        return null;
    }

    @Override
    public void pullTalkLog(TalkBackIntegrationConfigDTO configDTO) {
        // 拉取数据
        Map<String, Object> map = new HashMap<>();
        map.put("PageIndex", 1);
        map.put("CountPrePage", 100);
        List<TalkLogDTO> talkLogDTOS = talkBackMiLiHandler.queryTalkLog(configDTO, map);
        if (CollectionUtils.isEmpty(talkLogDTOS)) {
            return;
        }
        // 转换数据
        List<TalkRecord> talkRecords = this.handleLog(configDTO, talkLogDTOS);
        // 存储业务中台
        talkBackService.saveTalkRecordList(talkRecords);
    }

    private List<TalkRecord> handleLog(TalkBackIntegrationConfigDTO configDTO, List<TalkLogDTO> talkLogDTOS) {

        return null;
    }
}
